package org.example.consume;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.example.dto.entity.OperationLogs;
import org.example.dto.mapper.OpertionLogsMapper;
import org.example.mq.OperationLogEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

//消费者
@Service
@RocketMQMessageListener(topic = "log-topic", consumerGroup = "log-consumer-group")
@Slf4j
public class LogConsumer implements RocketMQListener<OperationLogEvent> {

    @Resource
    private OpertionLogsMapper logsMapper;




    @Override
    public void onMessage(OperationLogEvent event) {
        try {
            log.info("Received message: " + event);

            // 幂等校验
            Integer count = logsMapper.selectCountByMessageId(event.getMessageId());
            if (count != null && count > 0) {
                log.warn("重复消费，已跳过：{}", event.getMessageId());
                return;
            }

            OperationLogs logEntity = new OperationLogs();
            logEntity.setUserId(event.getUserId());
            logEntity.setAction(event.getAction());
            logEntity.setIp(event.getIp());
            logEntity.setDetail(event.getDetail()); // 记录操作详情（如修改字段）
            logEntity.setMessageId(event.getMessageId());

            logsMapper.insert(logEntity);
            log.info("日志落库成功: {}", event.getMessageId());
        } catch (Exception e) {
            log.error("消费日志失败，将自动重试: {}", e.getMessage(), e);
            // 抛异常，RocketMQ 会自动重试（默认16次）
            throw new RuntimeException(e);
        }

    }
}
